package seelction;

import java.util.Arrays;

/**
 * Created by mHandler on 2018/8/5 0005.
 * Description:
 */
public class OwnMergeSort {
    private OwnMergeSort(){}
    private static void merge(Comparable[] arr,int l,int mid,int r){
        Comparable[] aux = Arrays.copyOfRange(arr,l,r+1);
        int i = l,j = mid + 1;
        for (int k = l; k <= r; k++){
            if (i > mid ){
                arr[k] = aux[j-l];
                j++;
            }else if (j > r){
                arr[k] = aux[i-l];
                i++;
            }else if (aux[i-l].compareTo(aux[j-l]) < 0){
                arr[k] = aux[i-l];
                i++;
            }else {
                arr[k] = aux[j-l];
                j++;
            }
        }
    }
    private static void sort(Comparable[] arr,int l,int r){
        if (r-l <= 5){
            InsertionSort.sort(arr,l,r);
            return;
        }
        int mid = (l + r)/2;
        sort(arr,l,mid);
        sort(arr,mid + 1,r);
        if (arr[mid].compareTo(arr[mid + 1]) > 0)
            merge(arr,l,mid,r);
    }

    public static void sort(Comparable[] arr) {

        int n = arr.length;
        sort(arr, 0, n - 1);
    }

    public static void main(String[] args) {
        Integer[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 22, 2, 1};
        sort(arr,0,arr.length-1);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
